package com.chs.springai_alibaba;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Description;
import org.springframework.core.io.Resource;

@SpringBootApplication
public class SpringAiOpenAiApplication {

    private static final Logger logger = LoggerFactory.getLogger(SpringAiOpenAiApplication.class);
    public static void main(String[] args) {
        SpringApplication.run(SpringAiOpenAiApplication.class, args);
    }

    @Bean
    CommandLineRunner ingestTermOfServiceToVectorStore(EmbeddingModel embeddingModel, VectorStore vectorStore,
                                                       @Value("classpath:rag/rule.txt") Resource termsOfServiceDocs) {

        return args -> {
            // 获取文档内容转成向量
            vectorStore.write(new TokenTextSplitter().transform(new TextReader(termsOfServiceDocs).read()));

            // 相关性搜索
            vectorStore.similaritySearch("rule").forEach(doc -> {
                logger.info("Similar Document: {}", doc.getContent());
            });
        };
    }

    @Bean
    @Description("向量")
    public VectorStore vectorStore(EmbeddingModel embeddingModel) {
        return new SimpleVectorStore(embeddingModel);
    }
}
